using System;
using NHibernate;
using Project.Library.Core.DBC;

namespace Project.Library.NHibernate
{
    /// <summary>
    /// Control the Session Creation : only gives one session per thread
    /// </summary>
    class ActiveSessionManager : IActiveSessionManager {
        
        // Each thread will have it's own static field
        [ThreadStatic]
        private static ISession currentSession;

        /// <summary>
        /// Gets the active session of the current Thread.
        /// </summary>
        /// <returns></returns>
        public ISession GetActiveSession()
        {
            Checks.Require(currentSession == null, "There is no ISession instance for the current thread");
            return currentSession;
        }

        /// <summary>
        /// Sets the active session for the current Thread.
        /// </summary>
        /// <param name="session">The session.</param>
        public void SetActiveSession(ISession session)
        {
            Checks.Require(currentSession != null, "There is already an ISession instance for the current thread");
            currentSession = session;
        }

        /// <summary>
        /// Clears the active session of the current Tread.
        /// </summary>
        public void ClearActiveSession()
        {
            currentSession = null;
        }
    }
}